from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, render
from django.conf import settings


class UserInfo(object):
    def __init__(self, role, name, id):
        self.id = id
        self.role = role
        self.name = name
        self.menu_name = None
        self.text_list = []


class AuthMiddleware(MiddlewareMixin):

    def is_white_url(self, request):
        if request.path in settings.NB_WHITE_URL:
            return True

    def process_request(self, request):
        """校验用户是否已登录"""
        # 不需要登录就能访问的url
        if self.is_white_url(request):
            return

        # session中能获取到用户信息 则登录成功; 未登录跳转回登录页面
        # user_dict['role'], user_dict['name'], user_dict['id']
        user_dict = request.session.get(settings.NB_SESSION_KEY)
        if not user_dict:
            return redirect(settings.NB_LOGIN_URL)
        # 已登录
        # 后续会用到当前已登录的用户信息
        # request.session.get(settings.NB_SESSION_KEY)['id']
        # request.xxxx = '99'

        # 用户对象 已登录封装用户信息
        request.nb_user = UserInfo(**user_dict)
        # request.nb_user.id
        # request.nb_user.name
        # request.nb_user.role
        # print(request.nb_user.name)
        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        if self.is_white_url(request):
            return
        # 根据用户角色 获取自己具备的 所有的权限
        user_permission_dict = settings.NB_PERMISSION[request.nb_user.role]

        # 获取当前用户访问的URL
        current_name = request.resolver_match.url_name

        # 是否为公共权限
        if current_name in settings.NB_PERMISSION_PUBLIC:
            return

        # 判断是否在自己具备的权限
        if current_name not in user_permission_dict:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'status': False, 'detail': '无权访问'})
            return render(request, "permission.html")

        # 有权限
        text_list = []  # ['创建订单','订单列表']
        text_list.append(user_permission_dict[current_name]['text'])

        menu_name = current_name
        while user_permission_dict[menu_name]['parent']:
            menu_name = user_permission_dict[menu_name]['parent']
            text = user_permission_dict[menu_name]['text']
            text_list.append(text)

        text_list.append('首页')
        text_list.reverse()

        # 4.1 当前菜单的值
        request.nb_user.menu_name = menu_name
        # print('menu_name---------------------------------------------------------------', menu_name)  # ['level/list']
        # 4.2 路经导航
        request.nb_user.text_list = text_list
